package com.taijihuabao.common.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.taijihuabao.modules.controller.ChaimController;
import com.taijihuabao.modules.entity.ChaimDetailEntity;
import com.taijihuabao.modules.service.ChaimService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class EasyExcelListerner extends AnalysisEventListener <ChaimDetailEntity>{

    private List<ChaimDetailEntity> list = new ArrayList<>();
    //每次读取100条数据就进行保存操作
    private static final int BATCH_COUNT = 100;
    @Autowired
    private ChaimService chaimService;

    public EasyExcelListerner(ChaimService chaimService){
        this.chaimService=chaimService;
    }
    @Override
    public void invoke(ChaimDetailEntity data, AnalysisContext context) {
         data.setChaimCode(ChaimController.chaimCode);
         list.add(data);
         if(list.size() >= BATCH_COUNT){
             saveData();
             list.clear();
         }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println(list);
        saveData();
    }

    private void saveData() {
        for (ChaimDetailEntity chaimDetailEntity : list) {
            chaimService.insertChaimDetail(chaimDetailEntity);
        }
    }
}
